<%@ page contentType="text/html;charset=UTF-8" %>
<%@ include file="/WEB-INF/views/include/taglib.jsp"%>
<html>
<head>
	<title>发票登记信息管理</title>
	<meta name="decorator" content="default"/>
	<script src="${ctxStatic}/typeahead/bootstrap-typeahead.js" type="text/javascript"></script>
	<script type="text/javascript">
	if (!Array.prototype.map) {
	    Array.prototype.map = function(callback, thisArg) {
	        var T, A, k;
	        if (this == null) {
	            throw new TypeError(" this is null or not defined");
	        }

	        // 1. Let O be the result of calling ToObject passing the |this| value as the argument.
	        var O = Object(this);

	        // 2. Let lenValue be the result of calling the Get internal method of O with the argument "length".
	        // 3. Let len be ToUint32(lenValue).
	        var len = O.length >>> 0;

	        // 4. If IsCallable(callback) is false, throw a TypeError exception.
	        // See: http://es5.github.com/#x9.11
	        if (typeof callback !== "function") {
	            throw new TypeError(callback + " is not a function");
	        }

	        // 5. If thisArg was supplied, let T be thisArg; else let T be undefined.
	        if (thisArg) {
	            T = thisArg;
	        }

	        // 6. Let A be a new array created as if by the expression new Array(len) where Array is
	        // the standard built-in constructor with that name and len is the value of len.
	        A = new Array(len);

	        // 7. Let k be 0
	        k = 0;

	        // 8. Repeat, while k < len
	        while(k < len) {

	            var kValue, mappedValue;

	            // a. Let Pk be ToString(k).
	            //   This is implicit for LHS operands of the in operator
	            // b. Let kPresent be the result of calling the HasProperty internal method of O with argument Pk.
	            //   This step can be combined with c
	            // c. If kPresent is true, then
	            if (k in O) {

	                // i. Let kValue be the result of calling the Get internal method of O with argument Pk.
	                kValue = O[ k ];

	                // ii. Let mappedValue be the result of calling the Call internal method of callback
	                // with T as the this value and argument list containing kValue, k, and O.
	                mappedValue = callback.call(T, kValue, k, O);

	                // iii. Call the DefineOwnProperty internal method of A with arguments
	                // Pk, Property Descriptor {Value: mappedValue, : true, Enumerable: true, Configurable: true},
	                // and false.

	                // In browsers that support Object.defineProperty, use the following:
	                // Object.defineProperty(A, Pk, { value: mappedValue, writable: true, enumerable: true, configurable: true });

	                // For best browser support, use the following:
	                A[ k ] = mappedValue;
	            }
	            // d. Increase k by 1.
	            k++;
	        }

	        // 9. return A
	        return A;
	    };
	}
	
		$(document).ready(function() {
			//$("#name").focus();
			$("#inputForm").validate({
				submitHandler: function(form){
					if($("#transactId").val()==''){
						showTip("经办人不能为空！");
					}
					loading('正在提交，请稍等...');
					form.submit();
				},
				errorContainer: "#messageBox",
				errorPlacement: function(error, element) {
					$("#messageBox").text("输入有误，请先更正。");
					if (element.is(":checkbox")||element.is(":radio")||element.parent().is(".input-append")){
						error.appendTo(element.parent().parent());
					} else {
						error.insertAfter(element);
					}
				}
			});
			bindDel();
			$("#transactName").typeahead({
		        source: function (query, process) {
		            return $.ajax({
		                url: '${ctx}/sys/user/listData',
		                type: 'post',
		                data: {name: query},
		                success: function (result) {
		                	//result.list = ["Ahmedabad","Akola","Asansol","Aurangabad","Bangaluru","Baroda","Belgaon","Berhumpur","Calicut","Chennai","Chapra","Cherapunji"];
		                	if(result.list){
			                	 var resultList = result.list.map(function (item) {
			                        var aItem = { id: item.id, name: item.name };
			                        return JSON.stringify(aItem);
			                       }); 
		                    	return process(resultList);
		                	}
		                	//var resultList = "["+JSON.stringify({name:"Ahmedabad"})+"]";
		                	return process("");
		                },
		            })
		        },
	            matcher: function (obj) {
	                //var item = JSON.parse(obj);
	                //return ~item.name.toLowerCase().indexOf(this.query.toLowerCase())
	                return true;
	            },
	            sorter: function (items) {          
	                var beginswith = [], caseSensitive = [], caseInsensitive = [], item;
	                 while (aItem = items.shift()) {
	                     var item = JSON.parse(aItem);
	                     if (!item.name.toLowerCase().indexOf(this.query.toLowerCase())) beginswith.push(JSON.stringify(item));
	                     else if (~item.name.indexOf(this.query)) caseSensitive.push(JSON.stringify(item));
	                     else caseInsensitive.push(JSON.stringify(item));
	                 }
	                 return beginswith.concat(caseSensitive, caseInsensitive)
	             },
	             highlighter: function (obj) {
	                 var item = JSON.parse(obj);
	                 var query = this.query.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, '\\$&')
	                 return item.name.replace(new RegExp('(' + query + ')', 'ig'), function ($1, match) {
	                     return '<strong style="font-weight:bold;">' + match + '</strong>'
	                 })
	             },
	             enterCallbackFunc:function(query){
	            	 
			        },
	             updater: function (obj) {
	                 var item = JSON.parse(obj);
	                 $('#transactId').val(item.id);
	                 $('#transactId').attr("data-name",item.name);
	                 return item.name;
	             },
		        items: 20,            // 最多显示项目数量
		        display: "name",     // 默认的对象属性名称为 name 属性
		        val: "id"           // 默认的标识属性名称为 id 属性
		  });
			
			$("#reviewUser").typeahead({
		        source: function (query, process) {
		            return $.ajax({
		                url: '',//${ctx}/sys/user/listData
		                type: 'post',
		                data: {name: query},
		                success: function (result) {
		                	//result.list = ["Ahmedabad","Akola","Asansol","Aurangabad","Bangaluru","Baroda","Belgaon","Berhumpur","Calicut","Chennai","Chapra","Cherapunji"];
		                	if(result.list){
			                	 var resultList = result.list.map(function (item) {
			                        var aItem = { id: item.id, name: item.name };
			                        return JSON.stringify(aItem);
			                       }); 
		                    	return process(resultList);
		                	}
		                	//var resultList = "["+JSON.stringify({name:"Ahmedabad"})+"]";
		                	return process("");
		                },
		            })
		        },
		        enterCallbackFunc:function(query){
		        	if ($.trim(query) != ''){
		        		var _text = '<div class="teacher-lab smart-teacher">'+
						 '<span class="name" data-id="">'+query+'</span>'+
						 '<a class="delete-lab ft-12" href="javascript:;" style="">'+
						 '<img src="${ctxStatic}/images/close.png"/></a>'+
					 	 '</div>';
		        	     $(".reviewUsers").html($(".reviewUsers").html()+_text);
		        	     bindDel();
		        	}
		        	$("#reviewUser").val('')
		        },
		        shown:false,
	            matcher: function (obj) {
	                var item = JSON.parse(obj);
	                return ~item.name.toLowerCase().indexOf(this.query.toLowerCase())
	            },
	            sorter: function (items) {          
	                var beginswith = [], caseSensitive = [], caseInsensitive = [], item;
	                 while (aItem = items.shift()) {
	                     var item = JSON.parse(aItem);
	                     if (!item.name.toLowerCase().indexOf(this.query.toLowerCase())) beginswith.push(JSON.stringify(item));
	                     else if (~item.name.indexOf(this.query)) caseSensitive.push(JSON.stringify(item));
	                     else caseInsensitive.push(JSON.stringify(item));
	                 }
	                 return beginswith.concat(caseSensitive, caseInsensitive)
	             },
	             highlighter: function (obj) {
	                 var item = JSON.parse(obj);
	                 var query = this.query.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, '\\$&')
	                 return item.name.replace(new RegExp('(' + query + ')', 'ig'), function ($1, match) {
	                     return '<strong style="font-weight:bold;">' + match + '</strong>'
	                 })
	             },
	             updater: function (obj) {
	                 //var item = JSON.parse(obj);
	                 //$('#transactId').val(item.id);
	                 //$('#transactId').attr("data-name",item.name);
	                 //return item.name;
	                 //this.enterCallbackFunc(item.name)
	                 return "";
	             },
		        items: 20,            // 最多显示项目数量
		        display: "name",     // 默认的对象属性名称为 name 属性
		        val: "id"           // 默认的标识属性名称为 id 属性
		  });
			
			$(".btn-draft").click(function(){
				$.ajax({
	                url: '${ctx}/review/inv/validator',
	                type: 'post',
	                data: {reviewName: $("#reviewName").val(),reviewDate:$("#reviewDate").val(),reviewCode:$("#reviewCode").val(),id:$("#id").val()
	                	,transactId:$("#transactId").val()
	                },
	                success: function (result) {
	                	if(result=='success'){
							$("#status").val('0');
							$("#inputForm").submit();
	                	}else if(result!='1'){
	                		showTip(result);
	                	}else{//提示比对信息
	                		findSimilarList('0');
	                	}
	                },
	            });
			});
			
			$(".btn-submit").click(function(){
				buildNames();
					if($("#transactId").val()=='' && $("#reviewType").val()!='1' ){
						showTip("经办人不能为空");
						return false;
					}
					if($("#transactId").attr('data-name')!=$("#transactName").val()){
						showTip("请选择 经办人");
						return false;
					}
					$("#status").val('1');
					$("#inputForm").submit();
			});
		});
		
        function bindDel() {
              $(".delete-lab").click(function(){
             	$(this).parent().remove() ;
              })
        }
        function buildNames(){
        	var names = "";
        	$(".name").each(function(){
        		if($(this).attr("data-id")==""){
        		names += $(this).text()+"§";
        		}
        	})
        	$("#names").val(names);
        }
        
        if('0'=='${rtnCode}'){
        	top.$.jBox.close();	
        }
        
	</script>
	<style type="text/css">
	  .addTeacher-box .teacher-lab {
		    display: inline-block;
		    margin-bottom: 4px;
		    min-width: 50px;
		    height: 26px;
		    line-height: 26px;
		    border: 1px solid #ddd;
		    margin-right: 8px;
		    vertical-align: middle;
		}
            
   .addTeacher-box .teacher-lab .name {
	    padding-left: 5px;
	    box-sizing: border-box;
	    width: 58px;
	    font-size: 12px;
	    text-align: center;
	}
	.addTeacher-box .teacher-lab a {
    display: inline-block;
    float: right;
    padding: 0 4px;
	}

	.ft-12 {
	    font-size: 12px;
	}
	.listitem-onerow {
	    display: inline-block;
	    overflow: hidden;
	    text-overflow: ellipsis;
	    white-space: nowrap;
	}

	.typeahead{
	   min-width: 270px!important;
	}
	.control-users{
	  display: block;
	}
	
	</style>
</head>
<body>
	<c:if test="${review.operateFlag ne '9' }">
	<ul class="nav nav-tabs">
		<%-- <li><a href="${ctx}/inv/review/">评审信息列表</a></li> --%>
		<li class="active"><a href="${ctx}/inv/review/form?id=${review.id}">评审登记信息${not empty review.id?'修改':'添加'}</a></li>
	</ul>
	</c:if>
	
	<br/>
	<form:form id="inputForm" modelAttribute="review" action="${ctx}/inv/review/save" method="post" class="form-horizontal">
		<form:hidden path="id"/>
	    <form:hidden path="status"/>
	    <form:hidden path="operateFlag"/>
	    <input type="hidden" name="names" id="names"/>
		<sys:message content="${message}"/>		
		<div class="control-group">
			<label class="control-label">评审名称：</label>
			<div class="controls">
				<input type="text" name="reviewName" id="reviewName" value="${review.reviewName }" autocomplete="off" class="input-xlarge required" style="margin: 0 auto;" data-items="20" >
				
				<span class="help-inline"><font color="red">*</font> </span>
			</div>
		</div>
		<div class="control-group">
			<label class="control-label">评审日期：</label>
			<div class="controls">
				<input name="reviewDate" id="reviewDate" type="text" readonly="readonly" maxlength="20" class="input-medium Wdate required"
					value="<fmt:formatDate value="${review.reviewDate}" pattern="yyyy-MM-dd"/>"
					onclick="WdatePicker({dateFmt:'yyyy-MM-dd',isShowClear:false});"/>
				<span class="help-inline"><font color="red">*</font> </span>
			</div>
		</div>
		<div class="control-group">
			<label class="control-label">评审金额：</label>
			<div class="controls">
				<form:input path="reviewFee" htmlEscape="false" maxlength="100" class="input-xlarge number required"/>
				<span class="help-inline"><font color="red">*</font> </span>
			</div>
		</div>
		<div class="control-group">
			<label class="control-label">评审人数：</label>
			<div class="controls">
				<form:input path="reviewNum" htmlEscape="false" maxlength="100" class="input-xlarge number required"/>
				<span class="help-inline"><font color="red">*</font> </span>
			</div>
		</div>
		<div class="control-group control-users">
			<label class="control-label">评审人员：</label>
			<div class="controls">
				<div class="reviewUsers addTeacher-box" style="margin-top:5px;float:left; ">
				<c:if test="${not empty review.userList}">
					<c:forEach items="${review.userList }" var="item">
						 <div class="teacher-lab smart-teacher">
							 <span class="name" data-id="${item.id }">${item.user.name }</span>
							 <c:if test="${review.status eq '0' }">
							 <a class="delete-lab ft-12" href="javascript:;" style="">
							 <img src="${ctxStatic}/images/close.png"/></a>
							 </c:if>
						 </div>
					</c:forEach>
				</c:if>
				</div>
				<c:if test="${review.status eq '0' }">
				<div style="margin-left:5px;margin-top:3px;float:left;">
					<input type="text" name="reviewUser" id="reviewUser" htmlEscape="false" maxlength="100" class="input-small" autocomplete="off" data-provide="typeahead" />
					<span class="help-inline"><font color="red">输入姓名后，回车键添加</font> </span>
				</div>
				</c:if>
			</div>
		</div>
		
		<div class="control-group">
			<label class="control-label">任务号：</label>
			<div class="controls">
				<form:select path="taskNo" class="input-medium">
					<form:options items="${fns:getDictList('INV_TASK_NO')}" itemLabel="label" itemValue="value" htmlEscape="false"/>
				</form:select>
				<span class="help-inline"><font color="red">*</font> </span>
			</div>
		</div>
		
		<div class="control-group">
			<label class="control-label">经办人：</label>
			<div class="controls">
				<input type="hidden" name="transactId" id="transactId" value="${review.transactId }" data-name="${review.transactName  }"/>
				<input type="text" class="input-xlarge required"  autocomplete="off" name="transactName" id="transactName" value="${review.transactName }" style="margin: 0 auto;" data-provide="typeahead" data-items="30"/>
				<span class="help-inline"><font color="red">*</font> </span>
			</div>
		</div>
		<div class="control-group">
			<label class="control-label">录入人：</label>
			<div class="controls">
				<form:input path="createBy.name"  maxlength="100" readonly="true"/>
			</div>
		</div>
		<div class="control-group">
			<label class="control-label">录入日期：</label>
			<div class="controls">
				<input name="createDate" type="text" readonly="readonly" maxlength="20" 
					value="<fmt:formatDate value="${review.createDate}" pattern="yyyy-MM-dd HH:mm:ss"/>" />
			</div>
		</div>
		<div class="control-group">
			<label class="control-label">备注：</label>
			<div class="controls">
				<form:textarea path="remarks" htmlEscape="false" rows="4" maxlength="255" class="input-xxlarge "/>
			</div>
		</div>
		
		
		<c:if test="${review.operateFlag ne '9' }">
			<div class="form-actions">
			<c:if test="${review.status eq '0' }">
				<!-- <input id="btnSubmit" class="btn btn-primary btn-draft" type="button" value="保 存草稿"/>&nbsp; -->
				<input id="btnSubmit" class="btn btn-primary btn-submit" type="button" value="提交"/>&nbsp;
				<input id="btnCancel" class="btn" type="button" value="返 回" onclick="history.go(-1)"/>
			</c:if>
			</div>
		</c:if>
		
		<c:if test="${review.operateFlag eq '9' }">
			<div class="form-actions">
				<input id="btnSubmit" class="btn btn-primary btn-submit" type="button" value="提交"/>&nbsp;
			</div>
		</c:if>
	</form:form>
</body>
</html>